<template>
  <el-dialog :title="`${showText()}权限点`" :visible.sync="showDialog" width="600px" @close="close">
    <!-- 表单 -->
    <el-form ref="formData" v-loading="loading" element-loading-text="加载中..." label-width="auto" :model="formData" :rules="rules" status-icon>
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name" style="width:300px" size="mini" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code" style="width:300px" size="mini" />
      </el-form-item>
      <el-form-item label="权限描述">
        <el-input v-model="formData.description" style="width:300px" size="mini" />
      </el-form-item>
      <el-form-item label="开启">
        <el-switch
          v-model="formData.enVisible"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" @click="btnOk">确定</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getPermissionDetail, addPermission, updatePermission } from '@/api/permission.js'
export default {
  name: 'PermissionDialog',
  data() {
    return {
      loading: false,
      defaultData: {
        name: '', // 名称
        code: '', // 标识
        description: '', // 描述
        type: '', // 类型 该类型 不需要显示 因为点击添加的时候已经知道类型了
        pid: '', // 因为做的是树 需要知道添加到哪个节点下了
        enVisible: '0' // 默认关闭
      },
      formData: { ...this.defaultData },
      rules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
      },
      showDialog: false
    }
  },
  methods: {
    // 获取权限点详情
    async GetPermissionDetail(id) {
      this.loading = true
      this.formData = await getPermissionDetail(id)
      console.log(this.formData)
      this.loading = false
    },
    showText() {
      return this.formData.id ? '编辑' : '新增'
    },
    // 确定提交
    async btnOk() {
      this.$refs.formData.validate() // 表单校验
      let message = '添加权限成功'
      if (this.formData.id) {
        // 编辑
        const res = await updatePermission(this.formData)
        console.log(res)
        message = '编辑权限成功'
      } else {
        // 添加
        await addPermission(this.formData)
      }
      this.showDialog = false
      this.$emit('success')
      this.$message.success(message)
    },
    // 关闭弹框
    close() {
      this.showDialog = false
      this.formData = { ...this.defaultData }
      this.$refs.formData.resetFields() // 重置表单校验
      this.id = null
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog .el-dialog__body{
      display: flex;
      justify-content: center;
      align-items: center;
}
</style>
